package sample.koans

/**
 * Created by runjia on 17-6-2.
 */
val Int.isOdd: Boolean get() = this % 2 == 1

fun task(): List<Boolean> {
  fun Int.isEven(): Boolean = this % 2 == 0

  fun Int.odd() = this % 2 == 1

  return listOf(42.isOdd, 239.odd(), 294823098.isEven())
}

fun <K, V> buildMap(builderAction: HashMap<K, V>.() -> Unit): Map<K, V> {
  val map = HashMap<K, V>()
  map.builderAction()
  return map
}

fun usage(): Map<Int, String> {
  return buildMap {
    put(0, "0")
    for (i in 1..10) {
      put(i, "$i")
    }
  }
}

fun main(args: Array<String>) {
  println(task())

  println(usage())

  println("123".length2)

  println(
      StringBuilder("zhu").myInvoke { it.append("runjia") }
  )
}

fun <T> T.myApply(f: T.() -> Unit): T {
  this.apply(f)
  return this
}

fun <T> T.myInvoke(f: (T) -> Unit): T {
  f.invoke(this)
  return this
}

fun createString(): String {
  return StringBuilder().myApply {
    append("Numbers: ")
    for (i in 1..10) {
      append(i)
    }
  }.toString()
}

fun createMap(): Map<Int, String> {
  return hashMapOf<Int, String>().myApply {
    put(0, "0")
    for (i in 1..10) {
      put(i, "$i")
    }
  }
}

// Extensions are resolved statically: you cannot shadow a member function with an extension
val String.length2: Int get() = this.length * 2